/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.merchant.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.wealth.commodity.entity.Category;
import com.wealth.commodity.entity.Goods;
import com.wealth.commodity.enums.GoodsStatusEnum;
import com.wealth.commodity.repository.CategoryDao;
import com.wealth.commodity.service.ICommentService;
import com.wealth.commodity.service.IGoodsService;
import com.wealth.merchant.entity.BusinessDistrict;
import com.wealth.merchant.entity.Market;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.entity.MerchantPic;
import com.wealth.merchant.repository.MerchantDao;
import com.wealth.merchant.service.IBusinessDistrictService;
import com.wealth.merchant.service.IMerchantService;
import com.wealth.merchant.service.MerchantPicService;
import com.wealth.merchant.vo.MerchantVO;
import com.wealth.system.entity.Corporation;
import com.wealth.system.entity.Role;
import com.wealth.system.entity.User;
import com.wealth.system.repository.UserDao;
import com.wealth.system.service.ShiroUser;

import iaas.enums.StatusEnum;
import iaas.service.impl.BaseServiceImpl;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Component
public class MerchantServiceImpl extends BaseServiceImpl<Merchant> implements IMerchantService{

	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private ICommentService commentService;
	@Autowired
	private MerchantDao merchantDao;
	@Autowired
	private CategoryDao categoryDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private MerchantPicService merchantPicService;
	@Autowired
	private IBusinessDistrictService businessDistrictService;
	
	/** 保存商户 */
	@Override
	@Transactional
	public void saveMerchant(Merchant merchant,User user) throws Exception{
		User shiroUser = ShiroUser.getInstance().getUser();
		
		//用户
		List<Role> roles=new ArrayList<Role>();
		roles.add(new Role(3L));//给商户分配新增权限
		user.setRoleList(roles);
		
		user.setPassword(user.getUsername().substring(user.getUsername().length()-6, user.getUsername().length()));
		user.setStatus(StatusEnum.NORMAL.getValue());
		user.setCorp(new Corporation(1L));//平台管理员
		user.setCreator(shiroUser.getUsername());
		user.setCreatetime(new Date());
		userDao.save(user);
				
		//保存商户
		merchant.setStatus(StatusEnum.NORMAL.getValue());
		merchant.setCreator(shiroUser.getUsername());
		merchant.setCreateTime(new Date());
		merchant.getUserList().add(user);
		merchantDao.save(merchant);
		
		
		//商户图片
		List<MerchantPic> picList = merchant.getMerchantPicList();
		if(picList!=null&&picList.size()>0){
		for (MerchantPic pic : picList) {
			pic.setMerchant(merchant);
			merchantPicService.save(pic);
			}
		}
	}
	
	/** 保存商户 */
	@Override
	@Transactional
	public void updateMerchant(Merchant merchant) throws Exception {
			
				merchantDao.save(merchant);
		
				//删除商户之前关联的图片
				deletePics(merchant.getId());
				
				//页面传入的商户图片,新增
				List<MerchantPic> picList = merchant.getMerchantPicList();
				for (MerchantPic pic : picList) {
					if (pic.getId() == null && pic.getPicurl()!=null) {
						pic.setMerchant(merchant);	
						merchantPicService.save(pic);
					}
				}
	}
	
	/** 批量保存商户 */
	@Override
	@Transactional
	public boolean importFile(MultipartFile file, Long marketid, Long districtid) throws Exception {
		try {
			/** -------- 读取文件 -------- */
			//工作簿
			Workbook workbook = WorkbookFactory.create(file.getInputStream());		
			//工作表
			Sheet sheet =workbook.getSheetAt(0); 					
			//总行
			int rows = sheet.getLastRowNum();																
			//遍历行, r=0 对应说明文字
			List<Merchant> merchantList = Lists.newArrayList(); 
			List<User> userList = Lists.newArrayList(); 
			for (int r = 1; r<=rows; r++) {
				Row row  = sheet.getRow(r);
				if(row==null){
					continue;
				}
				//总列
				int cells = row.getLastCellNum();			
				//商户
				Merchant merchant = new Merchant();
				User user = new User();
				//遍历每一列
				for (int col = 0; col<cells; col++) {
					//设置每一列为字符串
					if(row.getCell(col)!=null){
						row.getCell(col).setCellType(Cell.CELL_TYPE_STRING);
					}
				}
				user.setUsername(row.getCell(0)==null?"":row.getCell(0).toString());
				merchant.setName(row.getCell(1)==null?"":row.getCell(1).toString());
				merchant.setLinkman(row.getCell(2)==null?"":row.getCell(2).toString());
				merchant.setTelephone(row.getCell(3)==null?"":row.getCell(3).toString());
				merchant.setAddress(row.getCell(4)==null?"":row.getCell(4).toString());
				merchant.setIntro(row.getCell(5)==null?"":row.getCell(5).toString());
				merchant.setChiefDishes(row.getCell(6)==null?"":row.getCell(6).toString());
				merchant.setType(0);// 0 普通商户
				merchantList.add(merchant);
				userList.add(user);
			}
			workbook.close();

			/** -------- 处理业务逻辑 -------- */
			//去重复,检验（未做）-->excel限制单元格
			
			//如果登录账号存在于数据库中，更新数据
			for (int i=0; i<userList.size()-1; i++) {
				User temp = userDao.findByUsername(userList.get(i).getUsername());
				if(temp!=null){
					//更新
					Merchant merchant  = merchantDao.findMerchantByUserId(temp.getId());
					merchant.setName(merchantList.get(i).getName());
					merchant.setLinkman(merchantList.get(i).getLinkman());
					merchant.setTelephone(merchantList.get(i).getTelephone());
					merchant.setAddress(merchantList.get(i).getAddress());
					merchant.setIntro(merchantList.get(i).getIntro());
					merchant.setMarket(new Market(marketid));
					merchant.setDistrict(new BusinessDistrict(districtid));
					merchant.setChiefDishes(merchantList.get(i).getChiefDishes());
					merchantDao.save(merchant);
				}else{
					//保存
					Merchant merchant = merchantList.get(i);
					merchant.setMarket(new Market(marketid));
					merchant.setDistrict(new BusinessDistrict(districtid));
					User user = userList.get(i);
					saveMerchant(merchant, user);
				}
			}
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} 
	}
	
	/**  查询商户 市场+状态 */
	@Override
	public List<Merchant> findByMarketIdAndStatus(Long marketId, Integer status) {
		return merchantDao.findByMarketIdAndStatus(marketId, status);
	}
	
	/**  查询商户 用户 */
	@Override
	public Merchant getMerchantByUserId(Long userid) throws Exception {
		return merchantDao.findMerchantByUserId(userid);
	}

	
	/** 
	 * 加载商户
	 * @param marketid  		市场
	 * @param categoryid 		分类
	 * @param districtid 		商圈
	 * @param status 			状态
	 * @param index				id从index开始
	 * @param offset 				查询offset条数据
	 */
	@Override
	public List<MerchantVO> ajaxMerchantVO(Long marketid, Long categoryid, Long districtid, Integer status, Integer index, Integer offset) throws Exception {
		
		/** ---- 组装vo ---*/
		//判断分类是否父节点，影响Dao层查询
		Category category = categoryDao.findOne(categoryid);
		Integer isParentCategory = 0;
		if(categoryid!=-1 && category.getPcategory()==null){
			isParentCategory = 1;
		}
		List<Merchant> polist = null;
		StringBuffer busId = new StringBuffer();
		//父类下所有的子类，busList 有数据表示查询条件为父类ID
	    List<BusinessDistrict> busList = businessDistrictService.getByParentIdAndStatus(districtid,StatusEnum.NORMAL.getValue());
	    busId.append(districtid);
	    if(busList.size()>0){
			
			for (int i = 0; i < busList.size(); i++) {
				 
				  busId.append(","+busList.get(i).getId());
			 
			} 
		} 
			
		polist = merchantDao.ajaxMerchant(marketid, categoryid ,districtid, isParentCategory, status,busId.toString(), index, offset);
			 
		List<MerchantVO> volist = new ArrayList<MerchantVO>();
		for (Merchant po : polist) {
			MerchantVO vo = new MerchantVO();
			Integer avgScore = commentService.getAvgScoreByMerchantId(po.getId());
			vo.setId(po.getId());
			vo.setName(po.getName());
			vo.setPicurl(po.getPicurl());
			vo.setAvgScore(avgScore);
			List<Goods> goodsList = goodsService.getGoodsByMerchantIdAndStatus(po.getId(), GoodsStatusEnum.UP.getValue());
			if(goodsList.size()>=1){
				vo.setGoodsName(goodsList.get(0).getName());
			}else{
				vo.setGoodsName("");
			}
			volist.add(vo);
		}
		return volist;
	}
	
	
	/** 搜索加载商户 */
	public List<MerchantVO> ajaxSearchMerchantVO(Long marketid,String name,  Integer status, Integer index,Integer offset) throws Exception{
		/** ---- 组装vo ---*/
		List<Merchant> polist = merchantDao.ajaxSearchMerchant(marketid, name, status, index, offset);
		
		List<MerchantVO> volist = new ArrayList<MerchantVO>();
		for (Merchant po : polist) {
			MerchantVO vo = new MerchantVO();
			Integer avgScore = commentService.getAvgScoreByMerchantId(po.getId());
			vo.setId(po.getId());
			vo.setName(po.getName());
			vo.setPicurl(po.getPicurl());
			vo.setAvgScore(avgScore);
			List<Goods> goodsList = goodsService.getGoodsByMerchantIdAndStatus(po.getId(), GoodsStatusEnum.UP.getValue());
			if(goodsList.size()>=1){
				vo.setGoodsName(goodsList.get(0).getName());
			}else{
				vo.setGoodsName("");
			}
			volist.add(vo);
		}
		return volist;
	}

	//查询参与打折的商户
	@Override
	public List<Merchant> getDiscountGoods(Integer isDiscount, Long maxid) {
		
		return merchantDao.getDiscountGoods(isDiscount, maxid);
	}
	
	//查询参与满减的商户
	@Override
	public List<Merchant> getFullcutMerchant(Integer isFullcut, Long maxid) {
		return merchantDao.getFullcutMerchant(isFullcut, maxid);
	}

	@Override
	public List<Merchant> findMerchantByType(int type) {
		 
		return merchantDao.findMerchantByType(type);
	}

	
	//删除商户之前的图片
	public void deletePics(Long merchantid)  throws Exception{
		
		List<MerchantPic> picsList = merchantPicService.findByPropertyName("merchant.id", merchantid, MerchantPic.class);
		for (MerchantPic pic : picsList) {
			merchantPicService.delete(pic);
		}
	}
	

}


